package com.android.dfsc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.dfsc.data.HrisCommObject;
import com.android.dfsc.data.HrisDeviceInfo;
import com.android.dfsc.data.HrisScenarioInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;

import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends DfscActivity {
	final int MENU_SYNC = Menu.FIRST;
	final int MENU_SYSTEM_SETTING = Menu.FIRST + 1;
	final int MENU_HOME = Menu.FIRST + 2;
	final int MENU_OUTSIDE = Menu.FIRST + 3;
	final int MENU_ABOUT = Menu.FIRST + 4;

	private List<Map<String, Object>> mData;
	
	private View activeItemView = null;
	private int activeItem = 0;

	
	private Activity context = this;

	private int[] imgResouceID = { R.drawable.scenario_small,
			R.drawable.light_small, R.drawable.curtain_small,
			R.drawable.ac_small, R.drawable.irda_small,
			R.drawable.heater_small, R.drawable.switch_small,
			R.drawable.security_small, R.drawable.setting };

//	private int[] imgBigResouceID = { R.drawable.scenario_big,
//			R.drawable.lights_big, R.drawable.curtain_big, R.drawable.ac_small,
//			R.drawable.irda_small, R.drawable.heater_big,
//			R.drawable.switch_small, R.drawable.security_big,
//			R.drawable.security_big };

	private String[] titleText;

	private String[] descText;

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// if (!
		// "1c.4b.d6.6e.ad.30".equals(SmartHomeEngine.getInstance().getWifiMacAddress()))
		// this.finish();
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		titleText = new String[] { getString(R.string.scenario_control),
				getString(R.string.light_control),
				getString(R.string.curtain_control),
				getString(R.string.aircon_control),
				getString(R.string.cinema_control),
				getString(R.string.warm_control),
				getString(R.string.switch_control),
				getString(R.string.safe_control),
				getString(R.string.system_setting) };

		descText = new String[] { getString(R.string.scenario_desc),
				getString(R.string.light_desc),
				getString(R.string.curtain_desc),
				getString(R.string.aircon_desc),
				getString(R.string.cinema_desc), getString(R.string.warm_desc),
				getString(R.string.switch_desc), getString(R.string.safe_desc),
				getString(R.string.setting_desc) };

		setContentView(R.layout.gshmain);
		
		//if (1 == 1) return;
		
		ListView list = (ListView) findViewById(R.id.mainItemListView);
		list.setDividerHeight(0);
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

		for (int i = 0; i < titleText.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", imgResouceID[i]);// 图像资源的ID
			map.put("ItemTitle", titleText[i]);
			map.put("ItemText", descText[i]);
			listItem.add(map);
		}

		SimpleAdapter listItemAdapter = new MyAdapter(this, listItem,// 数据源
				R.layout.gshmainitem,// ListItem的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemTitle", "ItemText" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.imageView1, R.id.textView1, R.id.textView2 });

		// list.setItemsCanFocus(false);
		// 添加并且显示
		list.setAdapter(listItemAdapter);

		// 添加点击
		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> listView, View currentView,
					int position, long id) {
				Log.d("honey-TEST", "in list click listener position = " + position + "  id = " + id );
				if (position == activeItem)
					return;
				
				if ( activeItemView != null)
					activeItemView.setBackgroundResource(R.drawable.maincellbk);
				
				
				activeItemView = listView.getChildAt(activeItem);
				if ( activeItemView != null)
					activeItemView.setBackgroundResource(R.drawable.maincellbk);
				
				currentView.setBackgroundResource(R.drawable.maincellselectedbk);
				//listView.getChildAt(position).setBackgroundResource(R.drawable.maincellselectedbk);
				activeItemView = currentView;
				activeItem = position;
				setLayout(activeItem);
				

			}

		});

		// setContentView(this.getMyView(0));
		mData = getData();
		
		ImageButton ibt = (ImageButton)findViewById(R.id.buttonHome);
		ibt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				GSmartHome.h1000Data.setActiveScenario(GSmartHome.SCENARIO_HOME);
				processScenarioCmd();
				
			}
		});
		
		ibt = (ImageButton)findViewById(R.id.buttonAway);
		ibt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				GSmartHome.h1000Data.setActiveScenario(GSmartHome.SCENARIO_AWAY);
				processScenarioCmd();
				
			}
		});
		
		Button  bt = (Button)findViewById(R.id.buttonSelectArea);
		bt.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Log.d("honey-TEST", "in text area touch listener");

				AlertDialog.Builder myBuilder = new AlertDialog.Builder(context);
				myBuilder.setTitle(context.getString(R.string.select_area));
				HrisCommObject[] areaList = GSmartHome.h1000Data.getAreaList();
				if (areaList.length <= 1) {
					// todo
					new AlertDialog.Builder(context)
							.setTitle(R.string.system_prompt)
							.setMessage(R.string.no_data)
							.setPositiveButton(R.string.ok,
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											// finish();
										}
									}).create().show();
					return ;
				}
				String[] areaNameBuffer = new String[areaList.length - 1];
				int i;
				for (i = 1; i < areaList.length; i++)
					areaNameBuffer[i - 1] = areaList[i].getName();

				for (i = 0; i < areaList.length; i++) {
					if (areaList[i].getId() == GSmartHome.h1000Data
							.getActiveArea()) {
						break;
					}
				}

				myBuilder.setSingleChoiceItems(areaNameBuffer, i - 1,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

								/* User clicked on a radio button do some stuff */
								GSmartHome.h1000Data
										.setActiveArea(GSmartHome.h1000Data
												.getAreaList()[whichButton + 1]
												.getId());
								setLayout(activeItem);
								dialog.cancel();
							}
						});

				AlertDialog myDialog = myBuilder.create();
				
				myDialog.show();
				
				Window mWindow = myDialog.getWindow();
			    WindowManager.LayoutParams lp = mWindow.getAttributes();
//			    lp.x= 300;
//			    lp.y= 100;
			    lp.width = 300;
			   
			    mWindow.setAttributes(lp);
			    
				
			}
		});
		setLayout(ActionType.ACTION_SCENARIO);
		//list.getChildAt(activeItem).setBackgroundResource(R.drawable.maincellselectedbk);
	}

	private void setLayout(int itemIndex){
		switch (itemIndex) {
		case ActionType.ACTION_LIGHT:
			new LightProcess(context).setLayout();
			break;
		case ActionType.ACTION_CURTAIN:
			new CurtainProcess(context).setLayout();
			break;
		case ActionType.ACTION_WARM:
			new WarmProcess(context).setLayout();
			break;
		case ActionType.ACTION_CINEMA:
			new CinemaProcess(context).setLayout();
			break;
		case ActionType.ACTION_SCENARIO:
			new ScenarioProcess(context).setLayout();
			break;
		case ActionType.ACTION_SWITCH:
			new RelayProcess(context).setLayout();
			break;
		case ActionType.ACTION_SAFE_ZONE:
			new SafeProcess(context).setLayout();
			break;
		case ActionType.ACTION_AIRCON:
			new AirconProcess(context).setLayout();
			break;
		case ActionType.ACTION_SETTING:
			new SettingProcess(context).setLayout();
			break;
			
		default:
			// todo
			// error process
		}
	}
	private List<Map<String, Object>> getData() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("title", getString(R.string.scenario_control));
		map.put("action_id", ActionType.ACTION_SCENARIO);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.light_control));
		map.put("action_id", ActionType.ACTION_LIGHT);

		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.curtain_control));
		map.put("action_id", ActionType.ACTION_CURTAIN);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.aircon_control));
		map.put("action_id", ActionType.ACTION_AIRCON);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.cinema_control));
		map.put("action_id", ActionType.ACTION_CINEMA);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.warm_control));
		map.put("action_id", ActionType.ACTION_WARM);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.switch_control));
		map.put("action_id", ActionType.ACTION_SWITCH);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.safe_control));
		map.put("action_id", ActionType.ACTION_SAFE_ZONE);
		list.add(map);
		map = new HashMap<String, Object>();
		map.put("title", getString(R.string.system_setting));
		map.put("action_id", ActionType.ACTION_SETTING);
		list.add(map);
		return list;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, MENU_SYNC, 0, getString(R.string.sync));
		menu.add(0, MENU_SYSTEM_SETTING, 0, getString(R.string.system_setting));
		menu.add(0, MENU_HOME, 0, getString(R.string.home));
		menu.add(0, MENU_OUTSIDE, 0, getString(R.string.outside));
		menu.add(0, MENU_ABOUT, 0, getString(R.string.about_title));

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case MENU_SYNC:
			Log.d("honey-TEST", "in MENU_SYNC");
			// result = SmartHomeEngine.getInstance().syncData();
			//processSyncCmd();

			break;
		case MENU_SYSTEM_SETTING:

			// LayoutInflater factory = LayoutInflater.from(this);
			// final View settingView = factory.inflate(R.layout.setting, null);
			//
			// AlertDialog dlg = new AlertDialog.Builder(this)
			// .setTitle(getString(R.string.setting))
			// .setView(settingView)
			// .setPositiveButton(getString(R.string.setting_ok), new
			// DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog, int whichButton) {
			//
			// //TODO
			// finish();
			//
			// /* User clicked OK so do some stuff */
			// }
			// })
			// .setNegativeButton(getString(R.string.setting_cancel), new
			// DialogInterface.OnClickListener() {
			// public void onClick(DialogInterface dialog, int whichButton) {
			// finish(); /* User clicked cancel so do some stuff */
			// }
			// }).create();
			// dlg.show();
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SettingActivity.class);
			startActivity(intent);
			Log.d("honey-TEST", "in MENU_SYSTEM_SETTING");
			break;
		case MENU_HOME:
			Log.d("honey-TEST", "in MENU_HOME");
			GSmartHome.h1000Data.setActiveScenario(2);
			//processScenarioCmd();
			// result = SmartHomeEngine.getInstance().sendCmdScenarioCfg(2);
			break;
		case MENU_OUTSIDE:
			Log.d("honey-TEST", "in MENU_OUTSIDE");
			GSmartHome.h1000Data.setActiveScenario(1);
			//processScenarioCmd();
			// result = SmartHomeEngine.getInstance().sendCmdScenarioCfg(1);
			break;
		case MENU_ABOUT: {
			Intent aboutIntent = new Intent();
			aboutIntent.setClass(MainActivity.this, AboutActivity.class);
			startActivity(aboutIntent);

			break;
		}
		}

		return true;
	}

	public static class ActionType {
		public static final int ACTION_SCENARIO = 0; /* 鍦烘櫙鎺у埗 */
		public static final int ACTION_LIGHT = 1; /* 鐏厜鎺у埗 */
		public static final int ACTION_CURTAIN = 2; /* 绐楀笜鎺у埗 */
		public static final int ACTION_AIRCON = 3; /* 绌鸿皟鎺у埗 */
		public static final int ACTION_CINEMA = 4; /* 褰遍煶绯荤粺 */
		public static final int ACTION_WARM = 5; /* 鍦版殩鎺у埗 */
		public static final int ACTION_SWITCH = 6; /* 寮�叧鎺у埗 */
		/* 瀹夐槻鎺у埗 */
		public static final int ACTION_SAFE_ZONE = 7;
		//public static final int ACTION_ZONE = 8;
		public static final int ACTION_SETTING = 8;
	}

	public class MyAdapter extends SimpleAdapter{

		public MyAdapter(Context context, List<? extends Map<String, ?>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			// TODO Auto-generated constructor stub
		}
		
		
		//@Override
				public View getView(int position, View convertView, ViewGroup parent) {

					convertView = super.getView( position, convertView,  parent);
					
					if (position == activeItem)
						convertView.setBackgroundResource(R.drawable.maincellselectedbk);
					else 
						convertView.setBackgroundResource(R.drawable.maincellbk);
					/*LayoutInflater mInflater = LayoutInflater.from(context);
					ViewHolder holder = null;
					if (convertView == null) {
						holder = new ViewHolder();
						convertView = mInflater.inflate(R.layout.mainitem, null);
						holder.img = (ImageView) convertView
								.findViewById(R.id.ItemImage);
						holder.title = (TextView) convertView
								.findViewById(R.id.ItemTitle);
						holder.info = (TextView) convertView
								.findViewById(R.id.ItemText);
						holder.icon = (ImageView) convertView
								.findViewById(R.id.IconImage);
						convertView.setTag(holder);

					} else {

						holder = (ViewHolder) convertView.getTag();
					}

					// if (position==1)
					// holder.img.setBackgroundResource((Integer)mData.get(position).get("img"));
					// holder.img.setBackgroundResource(R.drawable.listitembk);
					holder.title.setText((String) mData.get(position).get("title"));
					// holder.title.setTextColor();
					holder.info.setText((String) mData.get(position).get("info"));
					// holder.icon.setImageBitmap(mIcon1);
*/
					return convertView;
				}
	}

	protected void processScenarioCmd() {

		this.setSuccessfulFlag(1);
		showDialog(PROCESS_DIALOG);
		// if (true) return;
		ScenarioCmdThread ct = new ScenarioCmdThread();
		if (ct == null)
			return;
		ct.start();
		registerReceiver(processCmdReceiver,
				new IntentFilter("dfsc.processCMD"));
	}

	private class ScenarioCmdThread extends Thread {
		public void run() {

			// todo
			int result = SmartHomeEngine.getInstance().sendCmdScenarioCfg(
					GSmartHome.h1000Data.getActiveScenario());

			Intent intent = new Intent();
			intent.setAction("dfsc.processCMD");
			intent.putExtra("result", result);
			context.sendBroadcast(intent);
			if (true)
				return;

		}
	}
}